/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2019/1/1
 * Description : initialization
 */

var schedule = require('node-schedule');
var fs = require('fs');
var DataCtrl = require('./controls/data');
var FileOpera = require('./utils/fileOpera');
var Setting = require('./setting');
var CommonMethod = require('./utils/commonMethod');

module.exports = function () {
    //! set mark
    global.Inited = false;

    //! init checking parameter
    var initParams = {
        dataItem : false,
        process : false
    };

    //! init checing
    var initChecking = function () {
        if(initParams.dataItem && initParams.process){
            console.log('Initiazation finished!');
            global.Inited = true;
        }
    };

    //! check dir
    FileOpera.buildDir(CommonMethod.getDataPath(), function () {
        //! check all data
        DataCtrl.getAll(function (err, items) {
            if (err) {
                return console.log('Error in getting all data items!');
            }
            fs.readdir(Setting.filePath, function (err, files) {
                if (err) {
                    return console.log('Error in checking data folder!');
                }
                global.TotalSize = 0;
                var dataProcessingCount = 0;
                var cb = function (i, j) {
                    dataProcessingCount ++;
                    return function (err, result) {
                        dataProcessingCount --;
                        if (err) {
                            return console.log('Error in removing redundancy data item! ' + err.message);
                        }
                        console.log('Removing a redundancy data item!');
                        if(dataProcessingCount == 0){
                            console.log('Data item checking finished!');
                            initParams.dataItem = true;
                            initChecking();
                        }
                    }
                };

                var sign = false;
                for (var i = 0; i < items.length; i++) {
                    //! find extension
                    var ext = items[i].d_fullpath;
                    ext = ext.substr(ext.lastIndexOf('.') + 1);

                    var filename = items[i]._id + '.' + ext;

                    //! add file size
                    global.TotalSize += items[i].d_size;

                    var j;
                    for (j = 0; j < files.length; j++) {
                        if (files[j] == filename) {
                            files[j] = '';
                            break;
                        }
                    }

                    if (j == files.length) {
                        sign = true;
                        DataCtrl.removeDbItem(items[i]._id, cb(i,j));
                    }
                }
                if(!sign){
                    console.log('Data item checking finished!');
                    initParams.dataItem = true;
                    initChecking();
                }

                for (j = 0; j < files.length; j++) {
                    if (files[j] != '') {
                        FileOpera.rmdir(Setting.filePath + files[j]);
                    }
                }
                
                console.log('Process finished!');
                initParams.process = true;
                initChecking();
            });
        });
    });

    //! build schedule
    schedule.scheduleJob('0 20 4 * * *', function () {
        DataCtrl.removeOutDateData(function (err, result) {
            if (err) {
                console.log('Error in removing out-date data!')
            }
            else {
                console.log('Removing out-date data successfully! Date : ' + (new Date).toLocaleString());
            }
        });
    });
}